import React, { PropTypes, PureComponent } from 'react';
import { connect } from 'dva';
import { TableC } from '../../../comps';
import arrow from '../../../assets/busi/PortfolioManagement/portfolioTrackings/arrow.png';
import { fixedNum } from '../../../utils/utils';
import config from '../../../utils/tableMoreIdConfig';
const {
  portfolioManagement: { indexMonitoring },
} = config;
import { VTComponents, VTScroll } from 'virtualizedtableforantd';
import { isZiGuanEvir } from '../../../utils/commonFunc';

class TargetTable extends PureComponent {
  state = {
    industry: undefined,
    indexBtn: true,
    industryBtn: true,
    columns1: [], //主表监控
    dataSource1: [],
    expandedRowKeys: [],
    expanded: true,
    columns2: [], //指数看板
    dataSource2: [],
    columns3: [], //行业看板
    dataSource3: [],
  };

  componentDidMount() {
    // 父组件对本组件的引用
    this.props.onRef(this);
    this.setState(
      {
        industry: this.props.industry,
      },
      () => {
        this.getList();
        this.getIndexTable();
        this.getIndustryTable();
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (this.props.industry != nextProps.industry) {
      this.setState(
        {
          industry: nextProps.industry,
          expanded: true,
        },
        () => {
          this.getList();
          this.getIndexTable();
          this.getIndustryTable();
        },
      );
    }
  }

  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.tableTimer1);
    clearInterval(this.tableTimer2);
    this.tableTimer1 = null;
    this.tableTimer2 = null;
    this.setState = (state, callback) => {
      return;
    };
  }

  refresh = () => {
    this.setState({
      indexBtn: true,
      industryBtn: true,
    });
    this.getIndexTable();
    this.getList();
    this.getIndustryTable();
  };

  clearTime = () => {
    clearInterval(this.timer);
    this.timer = null;
    clearInterval(this.tableTimer1);
    clearInterval(this.tableTimer2);
    this.tableTimer1 = null;
    this.tableTimer2 = null;
  };

  //获取监控主表统计数据
  getList = () => {
    const { dispatch, indexCode } = this.props;
    const { industry, expanded } = this.state;
    dispatch({
      type: 'indexMonitoringM/getList',
      payload: {
        indexCode: indexCode,
        industry: industry,
      },
      callback: (res) => {
        this.setState(
          {
            columns1: res.columns,
            dataSource1: res.dataSource,
            expandedRowKeys: expanded && res.dataSource && res.dataSource.length > 0 ? [res.dataSource[0].id] : [],
          },
          () => {
            this.timeRefresh();
          },
        );
      },
    });
  };

  //获取指数看板统计数据
  getIndexTable = () => {
    const { dispatch, indexCode } = this.props;
    dispatch({
      type: 'indexMonitoringM/getIndexTable',
      payload: {
        indexCode: indexCode,
      },
      callback: (res) => {
        this.setState({
          columns2: res.columns,
          dataSource2: res.dataSource,
        });
      },
    });
  };

  //获取行业看板统计数据
  getIndustryTable = () => {
    const { dispatch, indexCode } = this.props;
    dispatch({
      type: 'indexMonitoringM/getIndustryTable',
      payload: {
        indexCode: indexCode,
      },
      callback: (res) => {
        this.setState({
          columns3: res.columns,
          dataSource3: res.dataSource,
        });
      },
    });
  };

  //指数看板
  changeIndexBtn = () => {
    this.setState(
      {
        indexBtn: !this.state.indexBtn,
        industryBtn: true,
      },
      () => {
        console.log(this.state.indexBtn);
        console.log(this.state.industryBtn);

        if (!this.state.indexBtn) {
          if (this.tableTimer1) clearInterval(this.tableTimer1);
          this.tableTimer1 = null;
          this.tableTimer1 = setInterval(() => {
            this.getIndexTable();
          }, 10000);
        } else {
          clearInterval(this.tableTimer1);
          this.tableTimer1 = null;
        }
      },
    );
  };

  //主表监控定时刷新
  timeRefresh = () => {
    const { dispatch, indexCode } = this.props;
    const { industry } = this.state;
    if (this.timer) clearInterval(this.timer);
    this.timer = null;
    this.timer = setInterval(() => {
      dispatch({
        type: 'indexMonitoringM/getList',
        payload: {
          indexCode: indexCode,
          industry: industry,
        },
        callback: (res) => {
          this.setState({
            columns1: res.columns,
            dataSource1: res.dataSource,
            expandedRowKeys: res.dataSource && res.dataSource.length > 0 ? [res.dataSource[0].id] : [],
          });
        },
      });
    }, 10000);
  };

  //行业看板
  changeIndustryBtn = () => {
    this.setState(
      {
        industryBtn: !this.state.industryBtn,
        indexBtn: true,
      },
      () => {
        if (!this.state.industryBtn) {
          if (this.tableTimer2) clearInterval(this.tableTimer2);
          this.tableTimer2 = null;
          this.tableTimer2 = setInterval(() => {
            this.getIndustryTable();
          }, 10000);
        } else {
          clearInterval(this.tableTimer2);
          this.tableTimer2 = null;
        }
      },
    );
  };

  changeColumns1 = (columns) => {
    let arr = columns;
    let { sortedInfo1 } = this.state;
    let sortedInfo = sortedInfo1 || {};
    arr.map((item) => {
      if (item.key == 'indexName' || item.key == 'tradingCode' || item.key == 'tradingName' || item.key == 'industry') {
        item.render = (text) => {
          return text ? text : '';
        };
      }
      if (item.key == 'realtimeWeight') {
        //实时权重
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text * 100, 2) : '';
        };
      }
      if (item.key == 'weight' || item.key == 'newValue') {
        //开盘权重、最新价
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text, 2) : '';
        };
      }
      if (item.key == 'tradeStatus') {
        item.width = '100px';
        (item.type = 'statusTip'),
          (item.tipValue = [
            {
              value: '0',
              title: '交易',
              class: 'tip-green',
            },
            {
              value: '1',
              title: '停牌',
              class: 'tip-grey',
            },
          ]);
      }
      if (item.key == 'revenue') {
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text, 4) : '';
        };
      }
      if (item.key == 'todayRate') {
        //涨跌幅
        item.type = 'columnView';
        item.percent = true;
        item.width = '14%';
      }
      if (item.key == 'todayRate' || item.key == 'weight' || item.key == 'realtimeWeight' || item.key == 'revenue' || item.key == 'tradeStatus' || item.key == 'industry') {
        //涨跌幅、开盘权重、实时权重、
        item.sorter = (a, b) => a[item.key] - b[item.key];
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
    });
    return arr;
  };

  //表格排序改变调用
  handleTableChange1 = (pagination, filter, sorter) => {
    this.setState({
      sortedInfo1: sorter,
    });
  };

  //父级元素的伸缩
  onExpand = (expanded, record) => {
    if (!expanded) {
      this.setState({
        expandedRowKeys: [],
        expanded: expanded,
      });
    } else {
      this.setState({
        expandedRowKeys: [record.id],
        expanded: expanded,
      });
    }
  };

  //指数看板
  fixedIndex = () => {
    const { indexBtn, industryBtn, columns2, dataSource2, columns3, dataSource3 } = this.state;
    const newColumns2 = this.changeColumns2(columns2);
    const newColumns3 = this.changeColumns3(columns3);

    let top = this.props.heightOrigin + 94 + 'px';
    return (
      <div className='fixed-box' style={{ top: top }}>
        {indexBtn ? (
          <div className='drawer-title' onClick={this.changeIndexBtn}>
            <span>指数看板</span>
            <img src={arrow} className='drawer-img' />
          </div>
        ) : (
          <div className='drawer-render'>
            <div className='drawer-render-title'>
              <span>指数看板</span>
              <img src={arrow} className='drawer-img' onClick={this.changeIndexBtn} />
            </div>
            <div>
              <TableC columns={newColumns2} dataSource={dataSource2} onChange={this.handleTableChange2} rowKey='id' hidePage={true} />
            </div>
          </div>
        )}
        <div style={{ height: '8px' }}></div>
        {industryBtn ? (
          <div className='drawer-title' onClick={this.changeIndustryBtn}>
            <span>行业看板</span>
            <img src={arrow} className='drawer-img' />
          </div>
        ) : (
          <div className='drawer-render'>
            <div className='drawer-render-title'>
              <span>行业看板</span>
              <img src={arrow} className='drawer-img' onClick={this.changeIndustryBtn} />
            </div>
            <div>
              <TableC scroll={{ y: 240 }} columns={newColumns3} dataSource={dataSource3} onChange={this.handleTableChange3} rowKey='id' hidePage={true} />
            </div>
          </div>
        )}
      </div>
    );
  };

  changeColumns2 = (columns) => {
    let arr = columns;
    let { sortedInfo2 } = this.state;
    let sortedInfo = sortedInfo2 || {};
    arr.map((item) => {
      if (item.key == 'denomination' || item.key == 'pe' || item.key == 'pb') {
        item.align = 'right';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text, 2) : '';
        };
      }
      if (item.key == 'indexCode' || item.key == 'indexName' || item.key == 'pe' || item.key == 'pb') {
        item.width = '100px';
      }
      if (item.key == 'todayRate') {
        //涨跌幅
        item.type = 'columnView';
        item.percent = true;
      }
      if (item.key == 'todayRate' || item.key == 'denomination' || item.key == 'pe' || item.key == 'pb') {
        //涨跌幅、开盘权重、实时权重、
        item.sorter = (a, b) => a[item.key] - b[item.key];
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
    });
    return arr;
  };

  //表格排序改变调用
  handleTableChange2 = (pagination, filter, sorter) => {
    this.setState({
      sortedInfo2: sorter,
    });
  };

  changeColumns3 = (columns) => {
    let arr = columns;
    let { sortedInfo3 } = this.state;
    let sortedInfo = sortedInfo3 || {};
    arr.map((item) => {
      if (item.key == 'weight') {
        //开盘权重
        item.align = 'right';
        item.width = '140px';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text, 2) : '';
        };
      }
      if (item.key == 'realtimeWeight') {
        //实时权重
        item.align = 'right';
        item.width = '140px';
        item.render = (text) => {
          return text !== null && text !== undefined ? fixedNum(text * 100, 2) : '';
        };
      }
      if (item.key == 'todayRate') {
        //涨跌幅
        item.type = 'columnView';
        item.percent = true;
      }
      if (item.key == 'todayRate' || item.key == 'weight' || item.key == 'realtimeWeight') {
        //涨跌幅、开盘权重、实时权重、
        item.sorter = (a, b) => a[item.key] - b[item.key];
        item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order;
      }
    });
    return arr;
  };

  //表格排序改变调用
  handleTableChange3 = (pagination, filter, sorter) => {
    this.setState({
      sortedInfo3: sorter,
    });
  };

  render() {
    const { heightOrigin, indexKey, loading } = this.props;
    const { columns1, dataSource1, expandedRowKeys, expanded } = this.state;
    const newColumns = this.changeColumns1(columns1);

    let height = isZiGuanEvir() ? heightOrigin + 220 + 'px' : heightOrigin + 280 + 'px';
    return (
      <div>
        <div style={{ marginTop: '20px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource1}
            scroll={{ x: '100%', y: `calc(100vh - ${height})` }}
            loading={loading.effects['indexMonitoringM/getList'] == true && dataSource1.length == 0}
            rowKey='id'
            onChange={this.handleTableChange1}
            expandedRowKeys={expandedRowKeys}
            onExpand={(expanded, record) => this.onExpand(expanded, record)}
            hidePage={true}
            components={
              expanded
                ? VTComponents({
                    id: indexKey + 1000,
                  })
                : undefined
            }
          />
        </div>
        {this.fixedIndex()}
      </div>
    );
  }
}
export default connect(({ indexMonitoringM, loading }) => ({ indexMonitoringM, loading }))(TargetTable);
